﻿using System;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using JsalesModel;
//using DevExpress.LocalizationCHS;


namespace JSales.ModuleSystem
{
    public partial class FormRoles : Form
    {
        public FormRoles()
        {
            InitializeComponent();
            InitValidationRules();
        }

        private EditMode mode;

        private enum EditMode
        {
            Normal = 0,
            Edit = 1,
            Add = 2
        }

        private void ChangeEditMode(EditMode editMode)
        {
            switch (editMode)
            {
                case EditMode.Normal:
                    {
                        mode = EditMode.Normal;

                        barButtonItemAdd.Enabled = true;
                        barButtonItemEdit.Enabled = true;
                        barButtonItemDelete.Enabled = true;
                        barButtonItemSave.Enabled = false;
                        barButtonItemCancel.Enabled = false;
                        
                        comboBoxRoles.Enabled = false;
                        comboBoxModel.Enabled = false;
                        checkEditAdd.Enabled = false;
                        checkEditDelete.Enabled = false;
                        checkEditSave.Enabled = false;
                        checkEditEdit.Enabled = false;
                        checkEditQuery.Enabled = false;
                        checkEditCommit.Enabled = false;
                        checkEditApproval.Enabled = false;
                        checkEditReject.Enabled = false;

                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        dxValidationProvider1.RemoveControlError(comboBoxRoles);
                        dxValidationProvider1.RemoveControlError(comboBoxModel);
                        dxValidationProvider1.RemoveControlError(checkEditAdd);
                        dxValidationProvider1.RemoveControlError(checkEditDelete);
                        dxValidationProvider1.RemoveControlError(checkEditSave);
                        dxValidationProvider1.RemoveControlError(checkEditEdit);
                        dxValidationProvider1.RemoveControlError(checkEditQuery);
                        dxValidationProvider1.RemoveControlError(checkEditCommit);
                        dxValidationProvider1.RemoveControlError(checkEditApproval);
                        dxValidationProvider1.RemoveControlError(checkEditReject);
                    }
                    break;
                case EditMode.Edit:
                    {
                        mode = EditMode.Edit;

                        barButtonItemAdd.Enabled = false;
                        barButtonItemEdit.Enabled = false;
                        barButtonItemDelete.Enabled = false;
                        barButtonItemSave.Enabled = true;
                        barButtonItemCancel.Enabled = true;

                        comboBoxRoles.Enabled = true;
                        comboBoxModel.Enabled = true;
                        checkEditAdd.Enabled = true;
                        checkEditDelete.Enabled = true;
                        checkEditSave.Enabled = true;
                        checkEditEdit.Enabled = true;
                        checkEditQuery.Enabled = true;
                        checkEditCommit.Enabled = true;
                        checkEditApproval.Enabled = true;
                        checkEditReject.Enabled = true;

                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;

                        dxValidationProvider1.Validate();
                    }
                    break;
                case EditMode.Add:
                    {
                        mode = EditMode.Add;

                        barButtonItemAdd.Enabled = false;
                        barButtonItemEdit.Enabled = false;
                        barButtonItemDelete.Enabled = false;
                        barButtonItemSave.Enabled = true;
                        barButtonItemCancel.Enabled = true;

                        comboBoxRoles.Enabled = true;
                        comboBoxModel.Enabled = true;
                        checkEditAdd.Enabled = true;
                        checkEditDelete.Enabled = true;
                        checkEditSave.Enabled = true;
                        checkEditEdit.Enabled = true;
                        checkEditQuery.Enabled = true;
                        checkEditCommit.Enabled = true;
                        checkEditApproval.Enabled = true;
                        checkEditReject.Enabled = true;

                        gridView1.OptionsBehavior.Editable = false;
                        gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.False;
                        //gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.None;
                        dxValidationProvider1.Validate();
                    }
                    break;
            }
        }

        private BindingSource bindingSource = new BindingSource();

        /// <summary>
        /// 编辑区初始化
        /// </summary>
        private void InitEditZone()
        {
            tbID.DataBindings.Clear();
            comboBoxRoles.DataBindings.Clear();
            comboBoxModel.DataBindings.Clear();
            checkEditAdd.DataBindings.Clear();
            checkEditDelete.DataBindings.Clear();
            checkEditEdit.DataBindings.Clear();
            checkEditQuery.DataBindings.Clear();
            checkEditSave.DataBindings.Clear();
            checkEditCommit.DataBindings.Clear();
            checkEditApproval.DataBindings.Clear();
            checkEditReject.DataBindings.Clear();

            if (bindingSource.Count>0)
            {
                tbID.DataBindings.Add("Text", bindingSource, "RoleId");
                comboBoxRoles.DataBindings.Add("SelectedIndex", bindingSource, "RoleName");
                comboBoxModel.DataBindings.Add("SelectedIndex", bindingSource, "Model");
                checkEditAdd.DataBindings.Add("EditValue", bindingSource, "Addition");
                checkEditDelete.DataBindings.Add("EditValue", bindingSource, "Delete");
                checkEditEdit.DataBindings.Add("EditValue", bindingSource, "Edit");
                checkEditQuery.DataBindings.Add("EditValue", bindingSource, "Query");
                checkEditSave.DataBindings.Add("EditValue", bindingSource, "Saves");
                checkEditCommit.DataBindings.Add("EditValue", bindingSource, "Commits");
                checkEditApproval.DataBindings.Add("EditValue", bindingSource, "Approval");
                checkEditReject.DataBindings.Add("EditValue", bindingSource, "Reject");
            }
        }

        /// <summary>
        /// 绑定数据
        /// </summary>
        private void BindData()
        {
            gridControl1.DataSource = bindingSource;
            repositoryItemLookUpEditModel.DataSource = GlobalVar.dtModl;
            repositoryItemLookUpEditRole.DataSource = GlobalVar.dtRoleName;

            comboBoxRoles.DataSource = GlobalVar.dtRoleName;
            comboBoxRoles.ValueMember = GlobalVar.dtRoleName.Columns["ID"].ToString();
            comboBoxRoles.DisplayMember = GlobalVar.dtRoleName.Columns["Name"].ToString();
            comboBoxModel.DataSource = GlobalVar.dtModl;
            comboBoxModel.ValueMember = GlobalVar.dtModl.Columns["ID"].ToString();
            comboBoxModel.DisplayMember = GlobalVar.dtModl.Columns["Name"].ToString();
            //comboBoxModel.Items.Clear();
            //
            //foreach (var v in typeof(GlobalVar.JYModels).GetFields())
            //{
            //    if (v.FieldType.IsEnum == true)
            //    {
            //        this.comboBoxModel.Items.Add(v.Name);
            //    }
            //}

        }

        /// <summary>
        /// 表格初始化
        /// </summary>
        private void InitGrid()
        {
            using (JYEntities dbContext = new JYEntities())
            {
                IQueryable<TbRole> Roles = from i in dbContext.TbRoles
                                               select i;

                    if (Roles.Any())
                    {
                        bindingSource.DataSource = Roles;
                        gridControl1.DataSource = bindingSource;
                    }

                BindData();
            }
        }


        private void InitValidationRules()
        {
            ConditionValidationRule notEmptyValidationRule = new ConditionValidationRule();
            notEmptyValidationRule.ConditionOperator = ConditionOperator.IsNotBlank;
            notEmptyValidationRule.ErrorText = "值不能为空！";

            dxValidationProvider1.ValidationMode = ValidationMode.Auto;

            dxValidationProvider1.SetValidationRule(comboBoxRoles, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(comboBoxModel, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditAdd, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditDelete, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditSave, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditEdit, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditQuery, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditCommit, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditApproval, notEmptyValidationRule);
            dxValidationProvider1.SetValidationRule(checkEditReject, notEmptyValidationRule);
        }

        private void ProductForm_Load(object sender, EventArgs e)
        {
            ChangeEditMode(EditMode.Normal);

            
            InitGrid();
            InitEditZone();
        }

        private void gridView1_RowClick(object sender, RowClickEventArgs e)
        {
            gridView1.RefreshData();
        }

        private void BarButtonAddItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Add);
            mode = EditMode.Add;

            barButtonItemSave.Enabled = true;
            barButtonItemCancel.Enabled = true;
            barButtonItemEdit.Enabled = false;
            barButtonItemDelete.Enabled = false;
            barButtonItemAdd.Enabled = false;

            tbID.DataBindings.Clear();
            comboBoxRoles.DataBindings.Clear();
            comboBoxModel.DataBindings.Clear();
            checkEditAdd.DataBindings.Clear();
            checkEditDelete.DataBindings.Clear();
            checkEditEdit.DataBindings.Clear();
            checkEditQuery.DataBindings.Clear();
            checkEditSave.DataBindings.Clear();
            checkEditCommit.DataBindings.Clear();
            checkEditApproval.DataBindings.Clear();
            checkEditReject.DataBindings.Clear();

            tbID.Text = null;
            comboBoxRoles.SelectedIndex = -1;
            comboBoxModel.SelectedIndex = -1;
            checkEditAdd.Checked = false;
            checkEditDelete.Checked = false;
            checkEditSave.Checked = false;
            checkEditEdit.Checked = false;
            checkEditQuery.Checked = false;
            checkEditCommit.Checked = false;
            checkEditApproval.Checked = false;
            checkEditReject.Checked = false;
        }

        private void barButtonEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ChangeEditMode(EditMode.Edit);
        }

        private void barButtonCancel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridControl1.FocusedView.CloseEditor();
            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (JYEntities dbContext = new JYEntities())
            {
                switch (mode)
                {
                    case EditMode.Normal:
                        break;
                    case EditMode.Add:
                        {
                            TbRole role =new TbRole();

                            role.RoleName = comboBoxRoles.SelectedIndex.ToString();
                            role.Model = comboBoxModel.SelectedIndex;
                            role.Addition = checkEditAdd.Checked;
                            role.Delete = checkEditDelete.Checked;
                            role.Edit = checkEditEdit.Checked;
                            role.Saves = checkEditSave.Checked;
                            role.Query = checkEditQuery.Checked;
                            role.Commits = checkEditCommit.Checked;
                            role.Approval = checkEditApproval.Checked;
                            role.Reject = checkEditReject.Checked;

                            dbContext.Add(role);
                            dbContext.SaveChanges();
                        }
                        break;
                    case EditMode.Edit:
                        {
                            IQueryable<TbRole> roles =
                                dbContext.TbRoles.Where(o => o.RoleId == int.Parse(tbID.Text));
                            if (roles.Any())
                            {
                                roles.FirstOrDefault().RoleName = comboBoxRoles.SelectedIndex.ToString();
                                roles.FirstOrDefault().Model = comboBoxModel.SelectedIndex;
                                roles.FirstOrDefault().Addition = checkEditAdd.Checked;
                                roles.FirstOrDefault().Delete = checkEditDelete.Checked;
                                roles.FirstOrDefault().Edit = checkEditEdit.Checked;
                                roles.FirstOrDefault().Saves = checkEditSave.Checked;
                                roles.FirstOrDefault().Query = checkEditQuery.Checked;
                                roles.FirstOrDefault().Commits = checkEditCommit.Checked;
                                roles.FirstOrDefault().Approval = checkEditApproval.Checked;
                                roles.FirstOrDefault().Reject = checkEditReject.Checked;

                                dbContext.SaveChanges();
                            }
                        }
                        break;
                }
            }
            ProductForm_Load(sender,e);
            ChangeEditMode(EditMode.Normal);
        }

        private void barButtonDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (var dbConText = new JYEntities())
            {
                IQueryable<TbRole> roles = from i in dbConText.TbRoles
                                                 where i.RoleId == int.Parse(tbID.Text)
                                                 select i;
                if (roles.Any())
                {
                    dbConText.Delete(roles.FirstOrDefault());
                    dbConText.SaveChanges();
                    ProductForm_Load(sender, e);
                }
            }
        }

        private void gridView1_ValidateRow(object sender, ValidateRowEventArgs e)
        {
            //GridView view = sender as GridView;
            //GridColumn IDColumn = view.Columns["ProductID"];
            //if (view.GetRowCellValue(e.RowHandle, IDColumn).Equals("") ||
            //    view.GetRowCellValue(e.RowHandle, IDColumn).Equals(null))
            //{
            //    e.Valid = false;
            //    view.SetColumnError(IDColumn, "产品ID不能为空！");
            //}

        }

        private void barButtonItemFind_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.FindPanelVisible = true;
        }
    }
}
